<script setup lang="ts">
import { type RouteRecordRaw, useRouter, useRoute } from 'vue-router'
import { defineProps, watch, onMounted, shallowRef, computed, type DefineComponent, ref } from 'vue'
import { adminRouter } from '@/modules/admin/router'
import { useCurrentUserStore } from '@/modules/security/stores/currentUserStores'
import { useRouterStore } from '@/modules/security/stores/routerStores'

const router = useRouter()
const route = useRoute()
const userStore = useCurrentUserStore()
const routerStore = useRouterStore()

interface Props {
  level1RouterPath: string;
}
const routes = ref<RouteRecordRaw[]>([])

const props = defineProps<Props>()

// 定义组件 props 和 emit 的类型
type ComponentProps = Record<string, unknown>

// 定义更精确的组件类型
type ComponentType = DefineComponent<ComponentProps>

// 使用 shallowRef 来存储异步加载的组件
const currentComponent = shallowRef<ComponentType | null>(null)

// 获取二级路由
const level2Routers = computed(() => {
  // 如果是首页路径，返回空数组
  if (props.level1RouterPath === '/admin') {
    return []
  }

  // 添加对 routes.value[0] 的检查
  if (!routes.value?.[0]) {
    return []
  }

  const selectedRoute = routes.value[0].children?.find(r => {
    return r.path === props.level1RouterPath
  })

  if (selectedRoute?.children) {
    // 过滤掉与父级路径相同的路由，但保留其他所有路由
    return selectedRoute.children.filter(r => 
      r.path !== selectedRoute.path && r.meta?.name
    ).map(route => {
      // 确保每个路由都有正确的路径和名称
      return {
        ...route,
        path: route.path || '',
        name: route.name || '',
        meta: route.meta || { name: '' }
      }
    })
  }
  return []
})

// 从路由配置中获取组件
const findRouteComponent = (routeName: string | symbol, routes: RouteRecordRaw[]): (() => Promise<{ default: ComponentType }>) | undefined => {
  for (const route of routes) {
    if (route.name === routeName && route.component) {
      return route.component as () => Promise<{ default: ComponentType }>
    }
    if (route.children) {
      const found = findRouteComponent(routeName, route.children)
      if (found) return found
    }
  }
  return undefined
}
watch(
  () => userStore.currentUser?.menus,
  (newMenus) => {
    if (newMenus) {
      routes.value = routerStore.getCurrentUserRouterRoot(newMenus,'admin')
    }
  },
  { immediate: true }
)
// 根据路由名称动态加载组件
watch(() => route.name, async (routeName) => {
  if (!routeName) {
    currentComponent.value = null
    return
  }

  try {
    // 从路由配置中查找对应的组件
    const componentLoader = findRouteComponent(routeName, adminRouter)
    if (componentLoader) {
      const module = await componentLoader()
      currentComponent.value = module.default
    } else {
      console.warn(`No component found for route: ${String(routeName)}`)
      currentComponent.value = null
    }
  } catch (error) {
    console.error('Failed to load component:', error)
    currentComponent.value = null
  }
}, { immediate: true })

/**
 * 获取需要展开的菜单路径列表
 */
const getDefaultParents = () => {
  const paths: string[] = []
  const matched = route.matched
  
  matched.forEach((record) => {
    if (record.path !== '/admin') {
      paths.push(record.path)
      // 如果有父级菜单，也添加到展开列表中
      if (record.meta?.parent) {
        const parentRoute = matched.find(r => r.name === record.meta.parent)
        if (parentRoute) {
          paths.push(parentRoute.path)
        }
      }
    }
  })
  
  return paths
}

/**
 * 处理菜单点击
 */
const handleMenuClick = (path: string) => {
  // 使用完整路径直接跳转
  router.push(path)
}

// 监听路由变化
watch(() => route.path, () => {
  getDefaultParents()
}, { immediate: true })

// 组件挂载时初化
onMounted(() => {
  getDefaultParents()
})
</script>

<template>
  <div class="admin-main">
    <el-container>
      <template v-if="level2Routers.length">
        <el-aside width="200px">
          <el-scrollbar>
            <el-menu 
              :default-active="route.path"
              :default-openeds="getDefaultParents()"
              :unique-opened="true"
            >
              <template v-for="route in level2Routers" :key="route.path">
                <!-- 有子菜单的情况 -->
                <el-sub-menu 
                  v-if="route.children && route.children.length > 0" 
                  :index="route.path"
                >
                  <template #title>
                    <span @click.stop="handleMenuClick(route.path)">
                      {{ route.meta?.name }}
                    </span>
                  </template>
                  <!-- 渲染子菜单 -->
                  <template v-for="subRoute in route.children" :key="subRoute.path">
                    <el-menu-item 
                      :index="subRoute.path"
                      @click="handleMenuClick(subRoute.path)"
                    >
                      {{ subRoute.meta?.name }}
                    </el-menu-item>
                  </template>
                </el-sub-menu>
                <!-- 没有子菜单的情况 -->
                <el-menu-item 
                  v-else 
                  :index="route.path"
                  @click="handleMenuClick(route.path)"
                >
                  {{ route.meta?.name }}
                </el-menu-item>
              </template>
            </el-menu>
          </el-scrollbar>
        </el-aside>
      </template>
      <el-main>
        <component
          v-if="currentComponent"
          :is="currentComponent"
        />
      </el-main>
    </el-container>
  </div>
</template>

<style scoped lang="scss">

</style>